using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using UnityEngine;
using System.IO;



public class RegexMgr : Singleton<RegexMgr> 
{
    readonly string RegexStr = @"(?<={0})([\s\S]*)(?={1})";

    //regex match string between begin and end
    public string RegexBeginAndEnd(string str,string begin,string end)
    {
        var regex = string.Format(RegexStr,begin,end);
        var match = Regex.Match(str,regex);
        if(match.Success)
        {
            return match.Value;
        }else{
            return "";
        }
    }

    //regex match string begin 
    public string RegexBegin(string str,string begin)
    {
        var regex = string.Format(RegexStr,begin,"");
        var match = Regex.Match(str,regex);
        if(match.Success)
        {
            return match.Value;
        }else{
            return "";
        }
    }

    //regex match string begin and end with replace
    public string RegexReplaceBeginAndEnd(string str,string begin,string end,string replace)
    {
        var regex = string.Format(RegexStr,begin,end);
        var match = Regex.Match(str,regex);
        if(match.Success)
        {
            return Regex.Replace(str,regex,replace);
        }else{
            return "";
        }
    }

    ///<summary>
    ///regex match namespace code and return class code
    ///default trim namespace
    ///example:
    ///namespace xxx
    ///{
    ///    public class xxx
    ///    {
    ///    }
    ///}
    ///</summary>
    ///return class code
    public string RegexNamespace(string str,bool trim = true)
    {
        var temp = RegexMgr.Instance.RegexBeginAndEnd(str,"namespace ","}");
        if(temp == "")
        {
            Debug.Log("RegexNamespace error");
            return "";
        }
        StringReader sr = new StringReader(temp.Trim());
        string line;
        int index = 0;
        var class_code = "";

        while((line = sr.ReadLine()) != null)
        {
            index++;
            if(index > 2)
            {
                var cd = "";
                if(trim)
                    cd = line.Length > 4 ? line.Substring(4) : line;
                else
                    cd = line;
                class_code += cd + "\n";
            }
        }

        sr.Close();

        return class_code;
    }
}